﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.BomCommand;

namespace SmartProduction.Write.API.Application.CommandHandlers.BomCommandHandler
{
    /// <summary>
    /// 处理配件添加命令
    /// </summary>
    public class BomPartsCreateCommandHandler : IRequestHandler<BomPartsCreateCommand, APIResult<object>>
    {
        /// <summary>
        /// 映射        
        /// /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 配件仓储
        /// </summary>
        private readonly IBaseRepository<BomParts> partsRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="partsRepository">配件仓储</param>
        public BomPartsCreateCommandHandler(IMapper mapper,IBaseRepository<BomParts> partsRepository)
        {
            this.mapper = mapper;
            this.partsRepository = partsRepository;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">操作</param>
        /// <returns>返回受影响行数</returns>
        public async Task<APIResult<object>> Handle(BomPartsCreateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var parts=mapper.Map<BomParts>(request);
            var i =  partsRepository.AddAsync(parts).Result;
            if (i > 0)
            {
                parts.PartsCode = "WHBL000001";
                int nums = 1;
                var temps = partsRepository.GetAll().Result.OrderByDescending(x => x.PartsCode).FirstOrDefault();
                if (temps != null)
                {
                    nums = Convert.ToInt32(temps.PartsCode.Replace("WHBL", ""));
                    nums++;
                }
                parts.PartsCode = "WHBL" + nums.ToString().PadLeft(5, '0');
            }
            return await Task.FromResult(result);
        }
    }
}
